import {
 Button, Checkbox, Divider, Input, Modal, Space, Spin,
} from 'antd'
import React, { PureComponent } from 'react'
import VirtualList from 'react-vlist'
import { filterSort, getElements } from './api'
import ResultTable from './ResultTable.jsx'
import { getProjectId } from '@/utils/https'
import styles from './index.less'

export default class ResultModal extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      visible: false,
      filtersObj: {},
      filters: {},
      data: [],
      searchInput: '',
      filtersArr: null,
      filterDropdownLoading: false,
    }
  }

  filterData = () => {
    const {
      targetTblName, orderByColName, order, filters,
    } = this.state
    const { columns } = this.props
    this.setState({ loading: true })
    const filterConditions = []
    for (const key in filters) {
      if (filters[key]) {
        filterConditions.push({
          columnName: columns[key],
          whereName: filters[key],
        })
      }
    }
    const postObj = {
      orderByColName,
      targetTblName,
      order,
      filterConditions,
    }
    filterSort(postObj).then(
      (res) => {
        this.setState({
          loading: false,
          data: res.rows || [],
        })
      },
      (error) => {
        this.setState({ loading: false })
      },
    )
  }

  // eslint-disable-next-line react/no-unused-class-component-methods
  openModal() {
    this.setState({
      visible: true,
      loading: true,
      targetTblName: this.props.targetTblName,
      data: this.props.rows,
    }, () => {
      getElements({ targetTblName: this.props.targetTblName }).then(
        (res) => {
          this.setState({
            filtersObj: res || {},
            loading: false,
          })
        },
        (error) => {
          this.setState({ loading: false })
        },
      )
    })
  }

  render() {
    const {
      loading, visible, filtersObj, data, searchInput, filtersArr, filterDropdownLoading,
    } = this.state
    const {
      columns,
    } = this.props
    return (
      <Modal
        title="指标结果"
        visible={visible}
        width={1120}
        onCancel={() => this.setState({ visible: false })}
        footer={[
          <Button key={1} onClick={() => this.setState({ visible: false })}>取消</Button>,
          <Button
            key={2}
            loading={loading}
            type="primary"
            download
            href={`${window.suanpan}/api/v1/index/indexListExport?targetTblName=${this.props.targetTblName}&projectId=${getProjectId()}`}
          >
            导出结果
          </Button>,
        ]}
        destroyOnClose
        bodyStyle={{
          paddingBottom: 0,
        }}
      >
        <Spin spinning={loading}>
          {
            visible && (
              <ResultTable
                columns={
                  columns.map((item, index) => (
                    {
                      title: item,
                      dataIndex: index,
                      key: index,
                      ellipsis: true,
                      sorter: true,
                      sortDirections: ['descend', 'ascend'],
                      filters: filtersObj[item] ? filtersObj[item].map((filt) => (
                        {
                          value: filt,
                        }
                      )) : [],
                      filterDropdown: ({
                        setSelectedKeys, selectedKeys, confirm, clearFilters, prefixCls, filters,
                      }) => {
                        const onChange = (value, checked) => {
                          if (checked) {
                            setSelectedKeys(selectedKeys.concat([value]))
                          } else {
                            const tempArr = []
                            selectedKeys.map((key) => {
                              if (key !== value) {
                                tempArr.push(key)
                              }
                            })
                            setSelectedKeys(tempArr)
                          }
                        }
                        return (
                          <Spin spinning={filterDropdownLoading}>
                            <div style={{ padding: 8 }}>
                              <Input
                                ref={node => {
                                  this.searchInput = node
                                }}
                                placeholder="在筛选项中搜索"
                                value={searchInput}
                                onChange={e => {
                                  this.setState({
                                    searchInput: e.target.value,
                                  }, () => {
                                    this.setState({
                                      filtersArr: filters.filter((arrnode) => arrnode.value.indexOf(e.target.value) > -1),
                                    })
                                  })
                                }}
                                onPressEnter={() => this.setState({
                                  filtersArr: filters.filter((arrnode) => arrnode.value.indexOf(searchInput || '') > -1),
                                })}
                                style={{ marginBottom: 8, display: 'block' }}
                              />
                              <Divider style={{ margin: '0.04rem 0' }} />
                              <VirtualList
                                className={styles.list}
                                data={filtersArr || filters}
                                itemheight={32}
                                renderItems={(listItem, listIndex, style) => (
                                  <div
                                    key={listIndex}
                                    style={style}
                                  >
                                    <Checkbox
                                      onChange={(e) => onChange(listItem.value, e.target.checked)}
                                      checked={selectedKeys.includes(listItem.value)}
                                    >
                                      {listItem.value}
                                    </Checkbox>
                                  </div>
                                )}
                              />
                              <Divider style={{ margin: '0.04rem 0' }} />
                              <Space>
                                <Button
                                  type="primary"
                                  onClick={() => confirm()}
                                  style={{ width: 90 }}
                                >
                                  搜索
                                </Button>
                                <Button
                                  onClick={() => {
                                    clearFilters()
                                    this.setState({
                                      searchInput: '',
                                    }, () => {
                                      this.setState({
                                        filtersArr: filters.filter((arrnode) => arrnode.value.indexOf('') > -1),
                                      })
                                    })
                                  }}
                                  style={{ width: 90 }}
                                >
                                  重置
                                </Button>
                              </Space>
                            </div>
                          </Spin>
                        )
                      },
                      filterSearch: (input, record) => record.value.indexOf(input) > -1,
                      width: columns.length > 8 ? 150 : undefined,
                      onFilterDropdownVisibleChange: dropdownVisible => {
                        if (dropdownVisible) {
                          this.setState({
                            filterDropdownLoading: true,
                            searchInput: '',
                          }, () => {
                            setTimeout(() => {
                              this.setState({
                                filtersArr: filtersObj[item] ? filtersObj[item].map((filt) => (
                                  {
                                    value: filt,
                                  }
                                )) : [],
                                filterDropdownLoading: false,
                              })
                              this.searchInput.select()
                            }, 100)
                          })
                        }
                      },
                    }
                  ))
                }
                dataSource={data}
                pagination={false}
                // scroll={{ x: columns.length > 9 ? (columns.length * 175) : undefined, y: 560 }}
                onChange={(paginationParams, filters, sorter, extra) => {
                  if (sorter.order) {
                    let order = ''
                    if (sorter.order === 'ascend') {
                      order = 'ASC'
                    } else if (sorter.order === 'descend') {
                      order = 'DESC'
                    }
                    this.setState({
                      order,
                      orderByColName: sorter.column.title,
                      filters,
                    }, () => {
                      this.filterData()
                    })
                  } else {
                    this.setState({
                      order: '',
                      orderByColName: '',
                      filters,
                    }, () => {
                      this.filterData()
                    })
                  }
                }}
              />
            )
          }
        </Spin>
      </Modal>
    )
  }
}
